package com.cml;

import com.cml.common.config.Configuration;
import com.cml.common.config.ConfigurationException;
import com.cml.common.constant.NodeStatus;
import com.cml.application.ServerNodeApplication;
import com.cml.common.context.ServerContext;
import com.cml.domain.builder.ServerNodeBuilder;
import com.cml.domain.entity.ServerNode;
import org.apache.log4j.Logger;

public class App 
{
    static  Logger logger = Logger.getLogger(App.class);
    /**
     * 系统关闭检查的时间间隔
     */
    private static final long SHUTDOWN_CHECK_INTERVAL = 10 * 1000;

    public static void main( String[] args )
    {
        try {
            String configFileName = "";
            if(args == null || args.length == 0){
                logger.warn("未指定配置文件，将使用默认配置文件！");
            }else{
                configFileName=args[0];
            }
            NodeStatus.getInstance().setCurStatus(NodeStatus.NODE_INIT);
            Configuration configuration = Configuration.getInstance();
            configuration.parse(configFileName);
            NodeStatus.getInstance().setCurStatus(NodeStatus.NODE_RUN);
            Thread serverThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    ServerContext serverContext = new ServerContext.Builder().build();
                    //启动节点
                    ServerNodeApplication serverNodeApplication = new ServerNodeApplication();
                    serverNodeApplication.start(serverContext);
                }
            });
            serverThread.setName("serverThread");
            serverThread.start();

            try {
                waitForShutdown();
            } catch (InterruptedException e) {
                logger.error(e);
                System.exit(1);
            }

        } catch (ConfigurationException e){
            logger.error("请正确配置配置文件",e);
        }catch (Exception e) {
            logger.error("系统发生未知性错误！",e);
        }
    }

    private  static void waitForShutdown() throws InterruptedException {
        while (true){
            if(NodeStatus.getInstance().isRunning()){
                Thread.sleep(App.SHUTDOWN_CHECK_INTERVAL);
            }else{
                logger.info("系统停止运行");
                break;
            }
        }
        System.exit(0);
    }
}
